import time
import docker
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response


def stop_container(id_or_name):
    try:
        client = docker.from_env()
        container = client.containers.get(f'{id_or_name}')  # 替换为你的容器名称
        container.restart()  # 停止容器
    except docker.errors.NotFound:
        print("Docker container not found.")
    except docker.errors.APIError as e:
        print(f"Docker API error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")


def common_exception_handler(exc, context):
    # 处理 DRF 异常
    res = drf_exception_handler(exc, context)

    if res:
        stop_container("9d42a5a4836a")  # 异常发生时停止容器
        stop_container("7bb558c7c23f")  # 异常发生时停止容器
        return Response({
            'code': 999,
            'msg': res.data.get('detail', "服务器出错, 请联系系统管理员")
        })
    else:
        stop_container("9d42a5a4836a")  # 异常发生时停止容器
        time.sleep(3)
        # 处理 Django 异常
        stop_container("7bb558c7c23f")  # 异常发生时停止容器
        return Response({
            'code': 998,
            'msg': str(exc)
        })
